<template>
	<view class="main">
		<view class="close" @click="toHome">
			<image src="../../static/image/login-close.png" mode=""></image>
		</view>
		<view class="login">
			{{$t('login.title')}}
		</view>
		<view class="register" @click="toRegister">
			{{$t('login.toRegister')}}
		</view>
		<uni-forms :modelValue="formData" label-position="top" v-if="isCode">
			<uni-forms-item :label="$t('login.tel')" name="tel">
				<text>+86</text>
				<uni-easyinput type="number" v-model="formData.tel" :placeholder="$t('login.doTel')" />
			</uni-forms-item>
			<uni-forms-item name="code" :label="$t('login.code')">
				<uni-easyinput type="text" v-model="formData.code" :placeholder="$t('login.doCode')" />
				<text class="codes" v-if="isShow" @click="code">{{$t("login.Code")}}</text>
				<text class="codes timer" v-else>{{$t("login.please")}}{{num}}{{$t('login.again')}}</text>
			</uni-forms-item>
		</uni-forms>
		<uni-forms :modelValue="formData" label-position="top" v-else>
			<uni-forms-item :label="$t('login.username')" name="tel">
				<!-- <text>+86</text> -->
				<uni-easyinput type="text" v-model="formData.username" :placeholder="$t('login.user')" />
			</uni-forms-item>
			<uni-forms-item name="" :label="$t('login.pass')">
				<uni-easyinput type="password" v-model="formData.password"
					:placeholder="$t('login.doPass')" />
			</uni-forms-item>
		</uni-forms>
		<button class="btn" type="primary" :class="{'dis':isDisabled}" :disabled="isDisabled"
			@click="login">{{$t('login.title')}}</button>
		<view class="retrieve-pass">
			<view class="left">
				<text v-if="isCode" @click="changeCode">{{$t("login.passLogin")}}</text>
				<text v-else @click="changeCode">{{$t("login.codeLogin")}}</text>
			</view>
			<text @click="toPass">{{$t('login.forgetPass')}}</text>
		</view>
		<view class="WXLogin">
			<view>{{$t('login.other')}}</view>
			<view class="wx_apple">
				<image src="../../static/image/WXlogo.png" mode="" @click="WXLogin"></image>
				<image v-if="system >= 13 && platform == 'ios'" src="../../static/image/apple.png" mode="" @click="appleLogin"></image>
			</view>
			<view class="privacy">
				{{$t("login.agree")}}<text @click="toPrivacyPolicy">{{$t("login.agreement")}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					tel: "",
					code: "",
					password: "",
					username:""
				},
				isShow: true,
				num: 60,
				isDisabled: true,
				isCode: false,
				pcode: "",
				system: '', //系统版本
				platform: '' // 平台
			}
		},
		watch:{
			formData:{
				deep:true,
				handler:function(newval,oldval){
					console.log(newval,oldval)
					if(this.isCode){
						if(newval.tel&&newval.code){
							this.isDisabled = false
						}else{
							this.isDisabled = true
						} 
					}else{
						if(newval.username&&newval.password){
							this.isDisabled = false
						}else{
							this.isDisabled = true
						} 
					}
				}
			}
		},
		methods: {
			/* 授权成功后的回调 */
			/*{
			    "errMsg": "getUserInfo:ok",
			    "rawData": "json字符串",
			    "userInfo": {
			        "openId": "xxx.xxxxx.xxx", // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
			        "fullName": {}, // 当且仅当第一次授权才会返回
			        "authorizationCode": "12345678xxx", // 服务器验证需要使用的参数
			        "identityToken": "header.payload.signature", // 服务器验证需要使用的参数
			        "realUserStatus": 1 // 用于判断当前登录的苹果账号是否是一个真实用户
			    },
			    "signature": ""
			}*/
			appleLogin () {
				// 判断是 iOS13+版本
				uni.login({
					provider: 'apple',
					success: (loginRes) => {
						uni.getUserInfo({
							provider: 'apple',
							success: (res) => {
								// 获取用户信息成功, info.authResult中保存登录认证数据
								console.log('获取用户信息成功 res', res)
								let data = {
									openId:res.userInfo.openId,
									fullName:res.userInfo.fullName,
									authorizationCode:res.userInfo.authorizationCode,
									identityToken:res.userInfo.identityToken,
									realUserStatus:res.userInfo.realUserStatus,
								}
								// 调用接口传递参数
							},
							fail: (err) => {
								// 登录授权失败
								// err.code错误码参考`授权失败错误码(code)说明`
							}
						})
					},
					fail: (err) => {
						console.log(err)
						uni.showModal({
							title: `登录失败${err}`
						})
					}
				})
			},
			changeCode() {
				uni.showLoading({
					mask:true
				})
				this.formData = {
					tel: "",
					code: "",
					password: "",
				}
				setTimeout(()=>{
				this.isCode = !this.isCode
				uni.hideLoading()
				},800)
			},
			//登录
			login() {
				let params = {
					methodtype: "",
					service: "moodle_mobile_app",
					phone: this.formData.tel,
					pcode: this.formData.code,
					username: this.formData.username,
					password: this.formData.password
				}
				
				if (this.isCode) {
					var reg = new RegExp(/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/)
					if (!reg.test(params.phone)) {
						uni.showToast({
							title: "请输入正确手机号",
							icon: "none"
						})
						return
					}
					params.methodtype = "pcode"
					if (this.Pcode != params.pcode) {
						uni.showToast({
							title: "验证码错误",
							icon: "none"
						})
						return
					}
				} else {
					if(!params.username ){
						uni.showToast({
							title: "请输入用户名",
							icon: "none"
						})
						return
					}
					if(!params.password){
						uni.showToast({
							title: "请输入密码",
							icon: "none"
						})
						return
					}
				 // params = {
					// 	methodtype: "usp",
					// 	service: "moodle_mobile_app",
					// 	username: this.formData.username,
					// 	password: this.formData.password
					// }
					params.methodtype = "usp"
				}
				uni.request({
					url: 'https://growlaasia.com/app/api/login.php',
					method: "POST",
					data: params,
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						console.log(res.data)
						if (res.data.errorcode == 200) {
							let token = JSON.stringify(res.data)
							uni.setStorageSync(
								'token',
								token
							)
							uni.showToast({
								title: "登录成功！",
								icon: "none"
							})
							uni.switchTab({
								url:'/pages/index/index'
							})
						} else {
							uni.showToast({
								title: "登录失败！",
								icon: "none"
							})
						}
					}
				})
			},
			//微信快捷登录
			WXLogin() {
				var that = this;
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						console.log(res.provider);
						//支持微信、qq和微博等
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									console.log("App微信获取用户信息成功", loginRes);
									// 获取用户信息
									uni.getUserInfo({
										provider: 'weixin',
										success: function(infoRes) {
											console.log('-------获取微信用户所有-----');
											console.log(infoRes.userInfo.openId);
											console.log(JSON.stringify(infoRes
												.userInfo));
											// 提交信息
											let params ={
												service:"moodle_mobile_app",
												token:loginRes.authResult.access_token,
												...infoRes.userInfo
											} 
										
											that.wxSubmit(params)
										}
									});
									// that.getApploginData(loginRes) //请求登录接口方法
								},
								fail: function(res) {
									console.log("App微信获取用户信息失败", res);
								}
							})
						}
					}
				});
			},
			// 提交微信用户信息
			wxSubmit(params) {
				this.$httpRequest({
					url: "app/api/loginbywechat.php",
					method: "POST",
					data: params
				})
				.then(res=>{
					if(res.token){
						let token = JSON.stringify(res)
						uni.setStorageSync("token",token)
						uni.reLaunch({
							url:"/pages/index/index"
						})
					}else if(res.error){
						uni.reLaunch({
							url:"/pages/bindPhone/bindPhone?openid="+params.openId
						})
					}else{
						uni.showToast({
							title:"登录失败",
							icon:"none"
						})
					}
				})
			},
			goback() {
				uni.reLaunch({
					url: "/pages/index/index"
				})
			},
			toHome() {
				uni.switchTab({
					url: "/pages/index/index"
				})
			},
			toRegister() {
				uni.navigateTo({
					url: "/pages/register/register"
				})
			},
			// 获取验证码
			code() {
			var reg = new RegExp(/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/)
			if (!reg.test(this.formData.tel)) {
				uni.showToast({
					title: "请输入正确手机号",
					icon: "none"
				})
				return
			}
			this.num = 60
				this.$httpRequest({
					url: "thirdcommon/mobile/src/sms.php",
					method: "POST",
					data: {
						phone: this.formData.tel
					}
				}).then(res => {
					console.log(res)
					if (res.msg == 200) {
						this.Pcode = res.code
						this.isShow = false
						let timer = setInterval(() => {
							this.num--
							if (this.num == 0) {
								this.isShow = true
								clearInterval(timer)
							}
						}, 1000)
					} else {
						uni.showToast({
							title: "获取失败",
							icon: "none"
						})
					}

				})

			},
			toPass() {
				uni.navigateTo({
					url: "/pages/RetrievePass/RetrievePass"
				})
			},
			toPrivacyPolicy() {
				uni.navigateTo({
					url: "/pages/privacyPolicy/privacyPolicy"
				})
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: (res) => {
					console.log('res========', res)
					this.system = parseInt((res.system).substring(4))
					console.log('处理后system', this.system)
					this.platform = res.platform
				}, 
				fail: (err) => {},
				complete: () => {}
			})
			uni.setStorageSync("isLogin", 1)
		}
		
	}
	
	
	
</script>

<style lang="scss" scoped>
	.main {
		width: 90%;
		margin: 0 auto;

		// .line {
		// 	width: 100%;
		// 	height: 2rpx;
		// 	background: #EBEDF0;
		// 	border-radius: 0px 0px 0px 0px;
		// 	opacity: 1;
		// 	// margin-top: -10rpx;
		// }

		::v-deep .is-input-border {
			border: none;
			border-bottom: 2rpx solid #ebedf0;
		}

		::v-deep .label-text {
			font-size: 28rpx;
			font-weight: 500;
			color: #0F1826;

		}

		::v-deep .uni-forms-item__label {
			width: 400rpx !important;
		}

		::v-deep .uni-forms-item__content {
			display: flex;
			align-items: center;
			margin-top: 20rpx;

			// text {
			// 	width: 60rpx;
			// }
			.codes {
				font-weight: 400;
				color: #4DBEC1;
				font-size: 28rpx;
			}

			.timer {
				opacity: .6;
			}

			.uni-easyinput {
				flex: 1;
			}
		}

		.close {
			margin: 120rpx 0 0;

			image {
				width: 64rpx;
				height: 64rpx;
			}
		}

		.login {
			font-size: 60rpx;
			font-weight: 500;
			color: #0F1826;
			margin: 64rpx 0 10rpx;
		}

		.register {
			font-size: 28rpx;
			font-family: PingFang TC-Regular, PingFang TC;
			font-weight: 400;
			color: #4DBEC1;
			margin-bottom: 104rpx;
		}

		.btn {
			margin-top: 66rpx;
			background-color: #4DBEC1;
			border: none;

			&.dis {

				background: rgba(77, 190, 193, 0.4);
			}
		}

		.retrieve-pass {
			margin-top: 32rpx;
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left {
				color: #4DBEC1;
			}
		}

		.WXLogin {
			position: fixed;
			left: 50%;
			bottom: 20rpx;
			width: 50%;
			text-align: center;
			font-weight: 400;
			color: #6E7580;
			font-size: 28rpx;
			margin-left: -25%;

			image {
				width: 84rpx;
				height: 84rpx;
				margin-top: 20rpx;
				margin-bottom: 20rpx;
			}
			
			.wx_apple {
				display: flex;
				justify-content: space-evenly;
			}

			.privacy {
				font-size: 24rpx;
				font-weight: 400;
				color: #A9AFB8;

				text {
					color: #4DBEC1;
				}
			}
		}
	}
</style>
